package com.efounder.activity;

import android.content.Intent;
import android.os.Bundle;

import com.core.xml.StubObject;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.NoticeCountEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.utils.ServiceUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.forwechat.BaseApp;
import com.efounder.frame.utils.Constants;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.ClearBadgeEvent;
import com.efounder.widget.EFImage;
import com.utilcode.util.AppUtils;
import com.utilcode.util.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import q.rorbin.badgeview.QBadgeView;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 首页TabBottomActivity基类，继承了BaseMainHomeActivity，
 * 增加了聊天相关的方法
 * 增加了角标初始化刷新的方法
 * @author wang
 */
public class BaseMainHomeWithChatActivity extends BaseMainHomeActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!checkChatUserValid()) {
            return;
        }
        // 从服务器请求联系人和群组数据
        requestUserChatInfo();
        //初始化角标
        BadgeUtil.initBadge();
        initBadge();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startService();
    }

    @Override
    public void refreshUi() {
        super.refreshUi();
        BadgeUtil.initBadge();
        initBadge();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initBadge() {
        if (null == mainMenuList) {
            return;
        }
        //不在列表里显示角标
        String chatIdNotReachedByChatListItem = "";
        for (int i = 0; i < mainMenuList.size(); i++) {
            if (i >= 5) {
                //最多只有五个菜单
                return;
            }
            StubObject stubObject = mainMenuList.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");
            List chatIDs = BadgeUtil.badgeMap.get(id);

            int unReadCount = BadgeUtil.getCount(id);

            EFImage efImage = tabbarView.getImageList().get(i);
            //设置角标的id和是否拖动
            efImage.setNodeId(id, draggable);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(BaseMainHomeWithChatActivity.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);

                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);
        }
    }

    /**
     * 开启服务
     */
    private void startService() {
        //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
        try {
            startService(new Intent(this, MessageService.class));

            if (!ServiceUtils.isServiceRunning(getApplicationContext(), SystemInfoService.class.getCanonicalName())) {
                String userId = EnvironmentVariable.getUserID();
                if (userId != null && !"".equals(userId)) {
                    startService(new Intent(this, SystemInfoService.class));
                }
            }
            if (!ServiceUtils.isServiceRunning(getApplicationContext(), OSPService.class.getCanonicalName())) {
                startService(new Intent(this, OSPService.class));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void requestUserChatInfo() {
        try {
            int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
            int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
            EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));
            //从服务器请求联系人和群组数据,以及自己的个人信息
            GetHttpUtil.getUserInfo(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                    BaseMainHomeWithChatActivity.this, new GetHttpUtil.GetUserListener() {
                        @Override
                        public void onGetUserSuccess(User user) {
                            EnvironmentVariable.setProperty(Constants.KEY_NICK_NAME, user.getNickName());
                        }

                        @Override
                        public void onGetUserFail() {

                        }
                    });
            GetHttpUtil.getUserData(this);
            GetHttpUtil.getGroupListByLoginId(this, null);
            GetHttpUtil.getAllOfficialNumber(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected boolean checkChatUserValid() {
        if (StringUtils.isEmpty(chatUserID) || StringUtils.isEmpty(chatPassword)) {
            try {
                AppUtils.relaunchApp(true);
                return false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        BadgeUtil.initBadge();
        initBadge();
        ((BaseApp) getApplicationContext()).setSystemInited(true);
    }

    //清除角标
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onClearBadgeEvent(ClearBadgeEvent event) {
        BadgeUtil.clearBadge(event.getNodeId());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        boolean mustRefresh = event.isRefreshAll();
        Long a1 = System.currentTimeMillis();
        for (int i = 0; i < mainMenuList.size(); i++) {
            StubObject stubObject = mainMenuList.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");
            List chatIds = BadgeUtil.badgeMap.get(id);
            if (!mustRefresh) {
                if (!BadgeUtil.isNeedRefreshBadge(chatIds, fromUserId, chatType)) {
                    continue;
                }
            }
            int unReadCount = BadgeUtil.getCount(id);
            EFImage efImage = tabbarView.getImageList().get(i);
            efImage.setNodeId(id, draggable);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(BaseMainHomeWithChatActivity.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);
                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);
        }

        int totalUnReadNum = 0;
        for (int i = 0; i < mainMenuList.size(); i++) {
            EFImage efImage = tabbarView.getImageList().get(i);
            int badgeNum = efImage.getBadgeCount();
            totalUnReadNum += badgeNum;
        }
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), totalUnReadNum);
    }
}
